package com.lance.answer.question_valid;

import com.google.common.collect.Lists;
import com.lance.answer.util.Constant;
import com.lance.answer.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.InputStream;
import java.util.*;

@Slf4j
public class QuestionValidFetchRetry {

    /**
     * 校验课程刷题情况
     *
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        //学科中文名
        String subjectName = "毛泽东思想和中国特色社会主义理论体系概论";
        //专业中文名
        String majorName = "all0624";
        //并发开启的浏览器数量
        int sync = 3;

        //是否提交答案
        boolean commit = false;
        //是否推送微信消息
        boolean push = false;
        //驱动路径
        String driverPath = null;

        //初始化日志配置
        Constant.initLog();

        StringBuilder sb = new StringBuilder();
        sb
                .append("校验课程")
                .append(" : ")
                .append(subjectName)
                .append("\n")

                .append("校验专业")
                .append(" : ")
                .append(majorName)
                .append("\n")

                .append("并发开启浏览器")
                .append(" : ")
                .append(sync)
                .append("\n");

        String message = sb.toString();
        System.out.println(message);
        if (push) {
            HttpClientUtil.send(message);
        }
        start(subjectName, majorName, sync, driverPath, commit, push);
    }

    public static void start(String subjectName, String majorName, int sync, String driverPath, boolean commit, boolean push) throws Exception {


        InputStream inputStream2 = Thread.currentThread().getContextClassLoader().getResourceAsStream(subjectName + "/" + "users/" + majorName + ".user");
        List<String> users = IOUtils.readLines(inputStream2, "utf-8");

        Map<String, String> userMap = new HashMap<>();
        for (String user : users) {
            String[] strs = user.split(",");
            String userCode = strs[0];
            String pwd = strs[1].substring(6, 14);
            userMap.put(userCode.trim(), pwd.trim());
        }


        File file = new File("src/main/resources/" + subjectName + "/valid_sections_error/");
        Collection<File> files = FileUtils.listFiles(file, null, false);
        List<String> userList = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(files)) {
            for (File file1 : files) {
                String fileName = file1.getName();
                String userName = fileName.replace(".json", "");
                if (userMap.containsKey(userName.trim())) {
                    userList.add(userName + "," + userMap.get(userName));
                }
            }
        }
        FileUtils.writeLines(new File("src/main/resources/" + subjectName + "/users/" + "retry.user"),userList);
    }
}
